import { DEFAULT_PROTABLE_OPTIONS } from '@/constants';
import {
  DownloadOutlined,
  LineChartOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable, StatisticCard } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Button, Card, Col, DatePicker, Row, Space, Tag, Tooltip } from 'antd';
import { useMemo, useRef, useState } from 'react';
import dayjs from 'dayjs';

import { getLoginLogListPaginated, getLoginStats, getDailyLoginCounts } from '@/services/operationLogApi';
import { Line } from '@ant-design/charts';

const { RangePicker } = DatePicker;
const { Statistic } = StatisticCard;

/**
 * 操作日志管理
 */
export default function OperationLogPage() {
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
  const tableActionRef = useRef<ActionType>();

  // 获取登录统计数据
  const { data: loginStats, loading: statsLoading } = useRequest(() => {
    const startTime = dateRange?.[0]?.format('YYYY-MM-DDTHH:mm:ss');
    const endTime = dateRange?.[1]?.format('YYYY-MM-DDTHH:mm:ss');
    return getLoginStats(startTime, endTime);
  }, {
    refreshDeps: [dateRange],
  });

  // 获取每日登录次数
  const { data: dailyLoginCounts, loading: chartLoading } = useRequest(() => {
    const startTime = dateRange?.[0]?.format('YYYY-MM-DDTHH:mm:ss');
    const endTime = dateRange?.[1]?.format('YYYY-MM-DDTHH:mm:ss');
    return getDailyLoginCounts(startTime, endTime);
  }, {
    refreshDeps: [dateRange],
  });

  // 日期范围变化处理
  const handleDateRangeChange = (dates: any) => {
    setDateRange(dates);
    // 刷新表格
    tableActionRef.current?.reload();
  };

  // 表格列定义
  const columns = useMemo<ProColumns<OPERATION_LOG.LoginLogModel>[]>(
    () => [
      {
        dataIndex: 'index',
        valueType: 'index',
        width: 48,
        title: '序号',
      },
      {
        dataIndex: 'username',
        title: '用户名',
        width: 120,
      },
      {
        dataIndex: 'loginIp',
        title: '登录IP',
        width: 120,
      },
      {
        dataIndex: 'loginDevice',
        title: '登录设备',
        width: 150,
      },
      {
        dataIndex: 'loginStatus',
        title: '登录状态',
        width: 100,
        valueEnum: {
          true: { text: '成功', status: 'Success' },
          false: { text: '失败', status: 'Error' },
        },
        render: (_, record) => {
          const status = record.loginStatus ? 'success' : 'error';
          const text = record.loginStatus ? '成功' : '失败';
          return <Tag color={status}>{text}</Tag>;
        },
      },
      {
        dataIndex: 'failReason',
        title: '失败原因',
        width: 150,
        hideInSearch: true,
        ellipsis: true,
        render: (_, record) => {
          return record.failReason || '-';
        },
      },
      {
        dataIndex: 'loginTime',
        title: '登录时间',
        width: 180,
        hideInSearch: true,
        render: (_, record) => {
          return record.loginTime ? dayjs(record.loginTime).format('YYYY-MM-DD HH:mm:ss') : '-';
        },
      },
      {
        dataIndex: 'logoutTime',
        title: '登出时间',
        width: 180,
        hideInSearch: true,
        render: (_, record) => {
          return record.logoutTime ? dayjs(record.logoutTime).format('YYYY-MM-DD HH:mm:ss') : '-';
        },
      },
      {
        dataIndex: 'sessionDuration',
        title: '会话时长',
        width: 120,
        hideInSearch: true,
        render: (_, record) => {
          if (!record.sessionDuration) return '-';
          const hours = Math.floor(record.sessionDuration / 3600);
          const minutes = Math.floor((record.sessionDuration % 3600) / 60);
          const seconds = record.sessionDuration % 60;
          return `${hours}时${minutes}分${seconds}秒`;
        },
      },
      {
        dataIndex: 'loginTime',
        title: '登录时间',
        hideInTable: true,
        valueType: 'dateRange',
        search: {
          transform: (value: any) => {
            return {
              startTime: value[0] ? dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
              endTime: value[1] ? dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
            };
          },
        },
      },
    ],
    [],
  );

  return (
    <PageContainer>
      {/* 统计卡片 */}
      <Card
        title="登录统计"
        extra={
          <Space>
            <RangePicker
              onChange={handleDateRangeChange}
              allowClear
              placeholder={['开始日期', '结束日期']}
            />
            <Tooltip title="刷新数据">
              <Button
                icon={<SearchOutlined />}
                onClick={() => {
                  // 刷新表格和统计数据
                  tableActionRef.current?.reload();
                }}
              />
            </Tooltip>
          </Space>
        }
        style={{ marginBottom: 24 }}
      >
        <Row gutter={24}>
          <Col span={6}>
            <Statistic
              title="总登录次数"
              value={loginStats?.data?.totalLogins || 0}
              loading={statsLoading}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="独立用户数"
              value={loginStats?.data?.uniqueUsers || 0}
              loading={statsLoading}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="平均每用户登录次数"
              value={loginStats?.data?.averageLoginsPerUser || 0}
              precision={1}
              loading={statsLoading}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="登录成功率"
              value={loginStats?.data?.successRate || 0}
              suffix="%"
              loading={statsLoading}
            />
          </Col>
        </Row>

        {/* 登录趋势图 */}
        <div style={{ height: 300, marginTop: 24 }}>
          <Line
            loading={chartLoading}
            data={dailyLoginCounts?.data || []}
            xField="date"
            yField="count"
            point={{ size: 5, shape: 'diamond' }}
            color="#1890ff"
            meta={{
              date: {
                alias: '日期',
              },
              count: {
                alias: '登录次数',
              },
            }}
          />
        </div>
      </Card>

      {/* 登录日志表格 */}
      <ProTable<OPERATION_LOG.LoginLogModel>
        headerTitle="登录日志"
        actionRef={tableActionRef}
        columns={columns}
        request={async (params) => {
          // 转换参数
          const { current, pageSize, ...rest } = params;
          // 添加日期范围
          const queryParams: OPERATION_LOG.LoginLogListParams = {
            pageNum: current,
            pageSize,
            ...rest,
          };
          
          // 如果有日期范围，添加到查询参数
          if (dateRange && dateRange[0] && dateRange[1]) {
            queryParams.startTime = dateRange[0].format('YYYY-MM-DDTHH:mm:ss');
            queryParams.endTime = dateRange[1].format('YYYY-MM-DDTHH:mm:ss');
          }
          
          // 调用API
          const res = await getLoginLogListPaginated(queryParams);
          return {
            data: res.data.list,
            success: res.code === 200,
            total: res.data.total,
          };
        }}
        {...DEFAULT_PROTABLE_OPTIONS}
        toolBarRender={() => [
          <Button
            key="export"
            type="primary"
            icon={<DownloadOutlined />}
            onClick={() => {
              // 导出功能，可以根据需要实现
              alert('导出功能待实现');
            }}
          >
            导出
          </Button>,
          <Button
            key="chart"
            icon={<LineChartOutlined />}
            onClick={() => {
              // 可以实现跳转到更详细的图表分析页面
              alert('图表分析功能待实现');
            }}
          >
            图表分析
          </Button>,
        ]}
      />
    </PageContainer>
  );
}